<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2022/12/5
 * Time: 13:34
 */

namespace app\controller\sys;
use app\model\sys\SysUser AS model;
use think\Exception;
use think\facade\Db;

class Login
{
    public function sign(){
        try {
            Db::startTrans();
            $username = input('username');
            $password = input('password');
            $find = model::where('username', $username)->where('status',1)->find();
            if (empty($find->user_id))
                throw new Exception('账号不存在', 400);
            if ($find->password != md5($password))
                throw new Exception('密码错误', 400);
            $token = md5(uniqid().rand(1000,9999));
            cache('Login:sys'.$token,$find);
            $data = $find->token;
            if (empty($data->user_id)) {
                $find->token()->save([
                    'token' => $token,
                    'espire_time' => now(),
                    'update_time' => now()
                ]);
            }else{
                $data->token = $token;
                $data->espire_time = now();
                $data->update_time = now();
                $data->save();
            }
            Db::commit();
            return json(['code' => 200,'msg' => '成功','data' => ['Api-Auth' => $token,'user' => $find]],200);
        }catch (\Exception $e){
            Db::rollback();
            return json(['code' => 401,'msg' => $e->getMessage(),'data' => []],400);
        }
    }
}